/**
 * 
 */
package d.qapaper.service;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Kaven
 * 
 */
public class ConfigReadService {
	private String preTAG;
	public HashMap<String, String> getConfig(InputStream inputStream) throws Exception {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		ReadHandler readHandler=new ReadHandler();
		parser.parse(inputStream, readHandler); 
		return readHandler.getConfigMap();
	}

	private class ReadHandler extends DefaultHandler {
		private HashMap<String, String> configMap;
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (preTAG != null) {
				String data = new String(ch, start, length);
				if ("title".equals(preTAG)) {
					configMap.put("title",data);
				} else if ("subTitle".equals(preTAG)) {
					configMap.put("subTitle",data);
				} else if ("cname".equals(preTAG)) {
					configMap.put("cname",data);
				}else if("unit".equals(preTAG)){
					configMap.put("unit",data);
				}else if("project".equals(preTAG)){
					configMap.put("project",data);
				}else if("item".equals(preTAG)){
					configMap.put("item",data);
				}else if("isUserPath".equals(preTAG)){
					configMap.put("isUserPath",data);
				}else if("userPath".equals(preTAG)){
					configMap.put("userPath",data);
				}else if("mID".equals(preTAG)){
					configMap.put("mID",data);
				}else if("isEncode".equals(preTAG)){
					configMap.put("isEncode",data);
				}else if("isZhcn".equals(preTAG)){
					configMap.put("isZhcn",data);
				}
			}
		}

		public HashMap<String, String> getConfigMap() {
			return configMap;
		}

		public void setConfigMap(HashMap<String, String> configMap) {
			this.configMap = configMap;
		}

		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
//			if("config".equals(localName))  
//            {  
//				configMap=new HashMap<String, String>();
//            }
			preTAG=localName;
		}

		public void startDocument() throws SAXException {
			configMap=new HashMap<String, String>();
		}

		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			preTAG=null;
		}
	}
}
